<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="./axios.min.js"></script>
  </head>
  <body>
    <input type="text" name="" id="" />
    <input type="text" name="" id="" />
    <input type="text" name="" id="" />
    <input type="text" name="" id="" />
    <button onclick="saveBtnClick()">保存</button>
    <script>
      // 1- 只要要修改的商品是谁
      // 2-把商品信息显示到输入框中
      // 保存按钮--点击保存 -- 发起修改请求

      console.log(location.search); //?pid=1212

      var parseQuery = function (query) {
        var reg = /([^=&\s]+)[=\s]*([^&\s]*)/g;
        var obj = {};
        while (reg.exec(query)) {
          obj[RegExp.$1] = RegExp.$2;
        }
        console.log(obj);
        return obj;
      };

      let obj = parseQuery(location.search.slice(1));
      console.log(obj);
      let { pid } = obj;

      //   2
      /* 
      根据商品 id 获取商品详情接口

     接口地址：http://jx.xuzhixiang.top/ap/api/detail.php
    接口请求方式：get
    接口参数：
    id  商品的id
    使用方式
    获取id为1的商品的详情
    http://jx.xuzhixiang.top/ap/api/detail.php?id=1
    服务器返回json数据
      
      */
      let detailAPI = "http://jx.xuzhixiang.top/ap/api/detail.php";
      axios
        .get(detailAPI, {
          params: {
            id: pid,
          },
        })
        .then((res) => {
          console.log(res.data);
          let pObj = res.data.data;
          let ipts = document.querySelectorAll("input");
          ipts[0].value = pObj.pname;
          ipts[1].value = pObj.pprice;
          ipts[2].value = pObj.pimg;
          ipts[3].value = pObj.pdesc;
        });

      /* 
        
          接口地址：    http://jx.xuzhixiang.top/ap/api/goods/goods-update.php
         接口请求方式：get
         接口参数：

    pid（必选）商品的id
    pname（必选）商品
    pprice（必选）商品
    pdesc（必选）商品
    使用方式
    pimg

    http://jx.xuzhixiang.top/ap/api/goods/goods-delete.php?pid=2459
        
        */
      async function saveBtnClick() {
        let ipts = document.querySelectorAll("input");
        let pname = ipts[0].value;
        let pprice = ipts[1].value;
        let pimg = ipts[2].value;
        let pdesc = ipts[3].value;

        let params = { pid, pname, pprice, pimg, pdesc };
        let updateProductAPI =
          "http://jx.xuzhixiang.top/ap/api/goods/goods-update.php";

        let res = await axios.get(updateProductAPI, { params });
        console.log(res.data);
        location.href = "index.html";
      }
    </script>
  </body>
</html>
